import html2Canvas from 'html2canvas';
import jsPDF from 'jspdf';
import {message} from "ant-design-vue";

const htmlToPdf = {
    getPdf(dom, param: any, callback?: Function,name?:any) {
        try {
            html2Canvas(dom, {
                scale: 2,
                allowTaint: true,
                useCORS: true,
            }).then(function (canvas) {
                let printWidth = 210 - Number(param.left) - Number(param.right)
                let printHeight = 297 - Number(param.top) - Number(param.bottom)
                let pdf = new jsPDF(dom, 'mm', 'a4'); //A4纸，纵向
                let ctx: any = canvas.getContext('2d', {willReadFrequently: true}),
                    a4w = printWidth,
                    a4h = printHeight,//A4大小，210mm x 297mm
                    imgHeight = Math.floor((a4h * canvas.width) / a4w), //按A4显示比例换算一页图像的像素高度
                    renderedHeight = 0;
                    ctx.mozImageSmoothingEnabled = false;
                    ctx.webkitImageSmoothingEnabled = false;
                    ctx.msImageSmoothingEnabled = false;
                    ctx.imageSmoothingEnabled = false;
                while (renderedHeight < canvas.height) {
                    let page: any = document.createElement('canvas');
                    page.width = canvas.width;
                    page.height = Math.min(imgHeight, canvas.height - renderedHeight); //可能内容不足一页
                    //用getImageData剪裁指定区域，并画到前面创建的canvas对象中
                    page.getContext('2d', {willReadFrequently: true}).putImageData(
                        ctx.getImageData(
                            0,
                            renderedHeight,
                            canvas.width,
                            Math.min(imgHeight, canvas.height - renderedHeight),
                        ),
                        0,
                        0,
                    );
                    pdf.addImage(
                        page.toDataURL('image/jpeg', 1.0),
                        'JPEG',
                        Number(param.left),//左
                        Number(param.top),//上
                        0,
                        Math.min(a4h, (a4w * page.height) / page.width),
                    );
                    renderedHeight += imgHeight;
                    if (renderedHeight < canvas.height) {
                        pdf.addPage(); //如果后面还有内容，添加一个空页
                    }
                }
                let win:any = window.open(pdf.output('bloburi'))
                if(name){
                    setTimeout(()=>{
                        win.document.title =name;
                    },1000)
                }
                callback && callback()
            })
        } catch (err: any) {
            message.error(err.message)
            callback && callback()
        }
    }
};

export default htmlToPdf;
